#include "ErnieDialog.h"
#include "ui_ErnieDialog.h"


ErnieDialog::ErnieDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ErnieDialog)
{
    ui->setupUi(this);
    //将photos目录拷贝到工程目录下
    loadPhotos("./photos");

    //初始化图片的索引
    m_index = 0;
    //设置随机数种子
    qsrand (QTime::currentTime().msec());
    //初始化摇奖状态
    isStarted = false;
}

ErnieDialog::~ErnieDialog()
{
    delete ui;
}

//绘图事件的处理函数
void ErnieDialog::paintEvent (QPaintEvent *)
{
    QPainter painter(this);
    //要绘图的区域
    QRect rcPhoto = ui->frame->frameRect();
    rcPhoto.translate (ui->frame->pos());
    painter.drawImage(rcPhoto, m_vecPhotos[m_index]);
}

//定时器处理函数
void ErnieDialog::timerEvent (QTimerEvent *)
{
    //随机获取一张图片的索引
    m_index = qrand() % m_vecPhotos.size();
    //触发绘图事件
    update();
}

//加载指定目录的图片
void ErnieDialog::loadPhotos (const QString& path)
{
    //创建目录对象
    QDir dir(path);
    //遍历目录中的普通文件
    foreach (QString file, dir.entryList(QDir::Files)) {
        QImage image(path + '/' + file);
        m_vecPhotos << image;
    }
    //遍历子目录
    foreach (QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
        loadPhotos(path + '/' + subDir);
    }
}

//开始摇奖(停止摇奖)按钮对应的槽函数
void ErnieDialog::on_pushButton_clicked()
{
    if (isStarted == false) {
        isStarted = true;
        m_idTimer = startTimer(100);//100ms
        ui->pushButton->setText("停止摇奖");
    } else {
        isStarted = false;
        killTimer(m_idTimer);
        ui->pushButton->setText("开始摇奖");
    }
}














